﻿using System.Reflection;
using Autofac;
using Microsoft.Extensions.DependencyInjection;
using ZilLion.Service.Core.Ioc;
using ZilLion.Service.Core.CRMUnities.Config;
using ZilLion.Service.Core.ConfigManager.Manager;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.AdvancedAPIs;
using Exceptionless.Json.Serialization;
using ZL.Web.Utility.Config;
using ZL.Web.Utility.Log;
using ZLWeb.WebApiRepository.Base;
using System.Threading.Tasks;
using ZLWeb.WebApiInfrastructure.Base;
using System;
using ZL.Web.Utility.Snowflake;
using ZLWeb.WebApiRepository.InterFace;
using ZLWeb.WebApiRepository;
using Senparc.Weixin;
using DapperWrapper;
using System.Collections.Generic;
using System.Threading;
using ZilLion.Service.Core.ModelBase;
using ZilLion.Service.Core.CRMUnities.IOC;
using ZLWeb.WebApiEntity.MemberCard;
using ZLWeb.WebApiEntityBase.RedisEntity;
using ZL.Web.Utility.Cache;
using ZLWeb.WebApiEntity.WechatCardModel;
using ZLWeb.WebApiEntityBase;
using System.Linq;
using Microsoft.AspNetCore.Hosting.Internal;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.Service.Core.WechatService.Domain;

namespace ZilLion.Service.Core.WechatService.Controller
{
    public class ComponentLoader : ComponentLoaderBase, IComponentLoader
    {
        public override void Register(ContainerBuilder builder)
        {
            base.Register(builder);
            RegisterAssemblis(Assembly.Load("ZilLion.Service.WechatService.Domain"));
            ConfigurationManager.SetAppSettings("Appid", ZilLionConfigurationManager.GetConfigInstance<WechatServiceConfig>().Appid);
            ConfigurationManager.SetConnectionStrings("DefaultConnection", ZilLionConfigurationManager.GetConfigInstance<WechatServiceConfig>().DefaultConnection);
            ConfigurationManager.SetConnectionStrings("DefaultConnection2", ZilLionConfigurationManager.GetConfigInstance<WechatServiceConfig>().DefaultConnection2);
            ConfigurationManager.SetConnectionStrings("DefaultConnection3", ZilLionConfigurationManager.GetConfigInstance<WechatServiceConfig>().DefaultConnection3);
            //SetWebApiJson();
            //SetAutofacWebAPIServices();
            LogHelper.LogConfigPath = FileHelper.GetRootPath() + "App_Data\\";
            ZL.Web.Utility.Config.GloabConfigLoader.InitGloabConfigLoader(new GloabConfigHandler(new WechatServiceContext()), FileHelper.GetRootPath() + "App_Data\\");
            SqlConnectionLoader.SetContext(new WechatServiceContext());
            SqlConnectionLoader.LoadSqlConnections();
            SqlConnectionLoader.LoadCheckDbConnections();
            GloabConfigCacheLoader CacheLoader = new GloabConfigCacheLoader(new ConfigCacheRepository(new WechatServiceContext()));
            CacheLoader.LoadCache();

            TaskFactory tf = new TaskFactory();
            if (!ZLConfig.IsDevModel)
            {
                Task task1 = tf.StartNew(TaskMethod_MemberCard);
            }

            //LogHelper.LogRunningException1(new ZLWeb.WebApiEntityBase.Error.RunningMessage() { Message = "435" });
            //AccessTokenContainer.Register(ZLConfig.TenPayV3.appid_j, ZLConfig.TenPayV3.AppSecret);

            long workerId = Convert.ToInt64(ZLConfig.WorkerId);
            //初始化单据生成器
            SnowflakeService.CreateSnoWorker(workerId);
            SnowflakeService.CreateIdWorker(workerId);
        }

        private void TaskMethod_MemberCard()
        {
            IPaymentRepository service = new PaymentRepository(new SourceBContext());
            while (true)
            {
                try
                {
                    Thread.Sleep(5000);
                    IEnumerable<ZLWeb.WebApiEntity.MemberCard.Wxmplist> xm = service.GetWxmpuinfo(ZLConfig.appid_j);
                    foreach (var plist in xm.OrderBy(tr => tr.msgdesc))
                    {
                        try
                        {
                            AccidModel Accid = SERedisHelper.Get<AccidModel>("2" + plist.uopenappid);
                            if (Accid == null)
                            {
                                service.SResultHandle(plist, "2", "错误码1404: 账号无法找到！" + plist.uopenappid);
                                continue;
                            }
                            var item = SqlConnectionLoader.ReadDbContextList.Cast<IMultiDbContext>()
                            .FirstOrDefault(tr => tr.mikey == Accid.ConstrName);
                            if (item == null) continue;
                            NamedParameter _contextdparameter = new NamedParameter("context", item);
                            NamedParameter _accidparameter = new NamedParameter("Accid", Accid.accid);
                            var paymentRepo = ClassFactory.GetInstance<IPaymentRepository>(_contextdparameter, _accidparameter);
                            WxShowInfo accInfoS = paymentRepo.GetAccWxShowInfo();
                            var accessToken = WeiXinContainer.GetAccessToken(ZLConfig.appid_j);
                            Senparc.Weixin.MP.AdvancedAPIs.Card.UpdateUserResult userInfo = new Senparc.Weixin.MP.AdvancedAPIs.Card.UpdateUserResult();
                            if (ZLConfig.IsSupportBalance)
                            {
                                userInfo = CardApi.UpdateUser(accessToken, accInfoS.ucode, accInfoS.ucardid, 0, 0,
                                null, accInfoS.accjf, (int)(accInfoS.accbalance * 100));
                            }
                            else
                            {
                                userInfo = CardApi.UpdateUser(accessToken, accInfoS.ucode, accInfoS.ucardid, 0, 0,
                                null, accInfoS.accjf);
                            }
                            if (!ZLConfig.IsSupportBalance)
                            {
                                string[] ids = plist.uopenappid.Split('|');
                                if (plist.msgtype == 1)
                                {
                                    SendTemplate(accessToken, ids[1], ZLConfig.AmountTemplateId, GetAmountMsgTemplate(plist.msgcontent));
                                }
                                if (plist.msgtype == 2)
                                {
                                    SendTemplate(accessToken, ids[1], ZLConfig.CouponTemplateId, GetCouponMsgTemplate(plist.msgcontent));
                                }
                            }
                            if (userInfo.errcode != ReturnCode.请求成功)
                            {
                                service.SResultHandle(plist, "1", userInfo.errmsg);
                            }
                            else
                            {
                                service.SResultHandle(plist, "0", userInfo.errmsg);
                            }
                        }
                        catch (NotFindAccidException Exception)
                        {
                            ErrorMessage msg = new ErrorMessage(Exception, "err");
                            string str = msg.Message;
                            if (str.Length > 100) str = str.Substring(0, 99);
                            service.SResultHandle(plist, "2", str);
                        }
                        catch (Exception exe)
                        {
                            ErrorMessage msg = new ErrorMessage(exe, "err");
                            string str = msg.Message;
                            if (str.Contains("43004") || str.Contains("账号无法找到"))
                            {
                                if (str.Length > 100) str = str.Substring(0, 99);
                                service.SResultHandle(plist, "2", str);
                            }
                            else
                            {
                                LogHelper.LogException(exe, "InnerTaskMethod_MemberCard", "ZLTProxy");
                                //if (str.Length > 100) str = str.Substring(0, 99);
                                //service.SResultHandle(plist, "1", str);
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    LogHelper.LogException(ex, "TaskMethod_MemberCard", "ZLTProxy");
                }
            }
        }


        private object GetAmountMsgTemplate(string msgcontent)
        {
            string[] msgs = msgcontent.Split('|');
            if (msgs.Length != 3) return null;
            var testData = new
            {

                first = new TemplateDataItem("帐户资金变动提醒:"),
                date = new TemplateDataItem(msgs[0]),
                adCharge = new TemplateDataItem(string.Format("¥{0}", msgs[1])),
                cashBalance = new TemplateDataItem(string.Format("¥{0}", msgs[2]))
            };
            return testData;
        }

        private object GetCouponMsgTemplate(string msgcontent)
        {
            string[] msgs = msgcontent.Split('|');
            if (msgs.Count() != 3) return null;
            var testData = new
            {
                first = new TemplateDataItem("积分变动通知: "),
                keyword1 = new TemplateDataItem("尊敬的客户"),
                keyword2 = new TemplateDataItem(msgs[0]),
                keyword3 = new TemplateDataItem(msgs[1]),
                keyword4 = new TemplateDataItem(msgs[2]),
                keyword5 = new TemplateDataItem("积分变动")
            };
            return testData;
        }


        private SendTemplateMessageResult SendTemplate(string accessToken, string openId, string TemplateId, object dy)
        {
            var result = TemplateApi.SendTemplateMessage(accessToken, openId, TemplateId, ZLConfig.RegesiterUrl, dy);
            return result;
        }


        //private void SetWebApiJson()
        //{
        //    var config = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        //    config.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        //    config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        //    //config.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        //    config.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
        //    config.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;

        //}

        ///// <summary>
        /////     注册并关联到系统DependencyResolver
        ///// </summary>
        //private static void SetAutofacWebAPIServices()
        //{
        //    ClassFactory.RegisterApiControllers(Assembly.Load("ZLWeb.WebApiControllers"));
        //    ClassFactory.RegisterAssemblis(Assembly.Load("ZLWeb.WebApiRepository"));
        //    ClassFactory.RegisterAssemblis(Assembly.Load("ZL.Web.Utility"));
        //    ClassFactory.RegisterDependencyResolver(GlobalConfiguration.Configuration.DependencyResolver);
        //}


    }
}